"use client"

import { useState, useEffect } from 'react'

interface JigsawPuzzleGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

interface PuzzlePiece {
  id: number
  content: string
  isPlaced: boolean
  correctPosition: number
}

export function JigsawPuzzleGame({ targetChar, onGameEnd }: JigsawPuzzleGameProps) {
  const [targetCharacter, setTargetCharacter] = useState('地')
  const [availablePieces, setAvailablePieces] = useState<PuzzlePiece[]>([])
  const [placedPieces, setPlacedPieces] = useState<(PuzzlePiece | null)[]>([null, null])
  const [score, setScore] = useState(0)
  const [timeLeft, setTimeLeft] = useState(60)
  const [level, setLevel] = useState(1)
  const [gameStarted, setGameStarted] = useState(false)
  const [isCompleted, setIsCompleted] = useState(false)

  // 初始化游戏
  useEffect(() => {
    initializeGame()
  }, [])

  // 计时器
  useEffect(() => {
    if (gameStarted && timeLeft > 0 && !isCompleted) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      onGameEnd(score, isCompleted ? 1 : 0, 1)
    }
  }, [timeLeft, gameStarted, score, isCompleted, onGameEnd])

  const initializeGame = () => {
    // 字根组合数据
    const puzzles = [
      { target: '地', pieces: ['土', '也'] },
      { target: '河', pieces: ['氵', '可'] },
      { target: '村', pieces: ['木', '寸'] },
      { target: '池', pieces: ['氵', '也'] },
      { target: '城', pieces: ['土', '成'] },
      { target: '林', pieces: ['木', '木'] }
    ]

    const currentPuzzle = puzzles.find(p => p.target === targetChar) || puzzles[0]
    setTargetCharacter(currentPuzzle.target)

    // 创建拼图片段
    const pieces: PuzzlePiece[] = currentPuzzle.pieces.map((piece, index) => ({
      id: index,
      content: piece,
      isPlaced: false,
      correctPosition: index
    }))

    // 打乱顺序
    const shuffledPieces = [...pieces].sort(() => Math.random() - 0.5)
    setAvailablePieces(shuffledPieces)
    setPlacedPieces(new Array(pieces.length).fill(null))
    setIsCompleted(false)
  }

  const handlePieceClick = (piece: PuzzlePiece) => {
    if (!gameStarted) setGameStarted(true)
    if (piece.isPlaced) return

    // 找到第一个空位置
    const emptyIndex = placedPieces.findIndex(p => p === null)
    if (emptyIndex === -1) return

    // 放置拼图片段
    const newPlacedPieces = [...placedPieces]
    newPlacedPieces[emptyIndex] = piece

    const newAvailablePieces = availablePieces.map(p => 
      p.id === piece.id ? { ...p, isPlaced: true } : p
    )

    setPlacedPieces(newPlacedPieces)
    setAvailablePieces(newAvailablePieces)

    // 检查是否完成
    if (newPlacedPieces.every(p => p !== null)) {
      checkCompletion(newPlacedPieces as PuzzlePiece[])
    }
  }

  const handlePlacedPieceClick = (index: number) => {
    const piece = placedPieces[index]
    if (!piece) return

    // 移回可用区域
    const newPlacedPieces = [...placedPieces]
    newPlacedPieces[index] = null

    const newAvailablePieces = availablePieces.map(p => 
      p.id === piece.id ? { ...p, isPlaced: false } : p
    )

    setPlacedPieces(newPlacedPieces)
    setAvailablePieces(newAvailablePieces)
  }

  const checkCompletion = (pieces: PuzzlePiece[]) => {
    // 检查是否按正确顺序排列
    const isCorrect = pieces.every((piece, index) => piece.correctPosition === index)
    
    if (isCorrect) {
      setScore(prev => prev + 100)
      setIsCompleted(true)
      setTimeout(() => {
        onGameEnd(score + 100, 1, 1)
      }, 2000)
    }
  }

  const resetGame = () => {
    setScore(0)
    setTimeLeft(60)
    setGameStarted(false)
    initializeGame()
  }

  const completeJigsaw = () => {
    if (placedPieces.every(p => p !== null)) {
      checkCompletion(placedPieces as PuzzlePiece[])
    }
  }

  return (
    <div className="h-full flex flex-col bg-white rounded-2xl p-6 relative">
      {/* 游戏标题和关闭按钮 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-green-500 rounded-lg flex items-center justify-center">
            <span className="text-white text-lg">🧩</span>
          </div>
          <h3 className="text-xl font-bold text-gray-800">字根拼图</h3>
        </div>
        <button
          onClick={() => onGameEnd(score, isCompleted ? 1 : 0, 1)}
          className="w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white hover:bg-red-600 transition-colors"
        >
          ✕
        </button>
      </div>

      {/* 游戏状态栏 */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{score}</div>
          <div className="text-sm text-gray-600">得分</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">
            {Math.floor(timeLeft / 60).toString().padStart(2, '0')}:
            {(timeLeft % 60).toString().padStart(2, '0')}
          </div>
          <div className="text-sm text-gray-600">时间</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{level}</div>
          <div className="text-sm text-gray-600">关卡</div>
        </div>
      </div>
      
      {/* 游戏区域 */}
      <div className="flex-1 flex flex-col items-center justify-center space-y-8">
        {/* 游戏说明和目标 */}
        <div className="text-center">
          <div className="text-lg font-bold text-gray-700 mb-2">🧩 字根拼图</div>
          <div className="text-sm text-gray-600 mb-4">将分散的字根拖拽组合成完整汉字</div>
          
          <div className="text-center">
            <div className="text-lg font-bold text-gray-700 mb-2">目标：</div>
            <div className="text-6xl font-bold text-gray-800 mb-4">{targetCharacter}</div>
          </div>
        </div>

        {/* 拼图区域 */}
        <div className="flex items-center justify-center space-x-4 mb-8">
          {placedPieces.map((piece, index) => (
            <div
              key={index}
              onClick={() => handlePlacedPieceClick(index)}
              className={`
                w-24 h-24 rounded-xl border-2 border-dashed border-gray-300 
                flex items-center justify-center cursor-pointer
                transition-all duration-300 hover:border-gray-400
                ${piece ? 'bg-blue-100 border-blue-400 border-solid' : 'bg-gray-50'}
              `}
            >
              {piece ? (
                <span className="text-2xl font-bold text-blue-700">
                  {piece.content}
                </span>
              ) : (
                <span className="text-gray-400 text-lg">+</span>
              )}
            </div>
          ))}
        </div>

        {/* 可用字根 */}
        <div className="flex flex-wrap justify-center gap-4">
          {availablePieces.filter(piece => !piece.isPlaced).map((piece) => (
            <div
              key={piece.id}
              onClick={() => handlePieceClick(piece)}
              className="w-20 h-20 bg-gray-200 rounded-xl flex items-center justify-center cursor-pointer
                       transition-all duration-300 hover:bg-gray-300 hover:scale-105 shadow-lg"
            >
              <span className="text-xl font-bold text-gray-700">
                {piece.content}
              </span>
            </div>
          ))}
        </div>

        {/* 完成按钮 */}
        <button 
          onClick={completeJigsaw}
          disabled={placedPieces.some(p => p === null)}
          className={`
            px-8 py-3 rounded-full font-bold text-lg transition-all duration-300
            ${placedPieces.every(p => p !== null)
              ? 'bg-blue-500 text-white hover:bg-blue-600 cursor-pointer'
              : 'bg-gray-300 text-gray-500 cursor-not-allowed'
            }
          `}
        >
          完成拼图
        </button>

        {/* 完成提示 */}
        {isCompleted && (
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600 mb-2">🎉 拼图完成！</div>
            <div className="text-lg text-gray-600">恭喜你成功组成了"{targetCharacter}"字！</div>
          </div>
        )}
      </div>

      {/* 底部控制按钮 */}
      <div className="flex justify-center space-x-4 mt-6">
        <button 
          onClick={() => setGameStarted(!gameStarted)}
          className="px-6 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors flex items-center space-x-2"
        >
          <span>{gameStarted ? '⏸️' : '▶️'}</span>
          <span>{gameStarted ? '暂停' : '开始'}</span>
        </button>
        <button 
          onClick={resetGame}
          className="px-6 py-2 bg-orange-500 text-white rounded-full hover:bg-orange-600 transition-colors flex items-center space-x-2"
        >
          <span>🔄</span>
          <span>重新开始</span>
        </button>
        <button className="px-6 py-2 bg-green-500 text-white rounded-full hover:bg-green-600 transition-colors flex items-center space-x-2">
          <span>⏭️</span>
          <span>下一关</span>
        </button>
        <button 
          onClick={() => onGameEnd(score, isCompleted ? 1 : 0, 1)}
          className="px-6 py-2 bg-gray-500 text-white rounded-full hover:bg-gray-600 transition-colors flex items-center space-x-2"
        >
          <span>🚪</span>
          <span>退出游戏</span>
        </button>
      </div>
    </div>
  )
} 